package com.mrjy.common.handler;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mrjy.common.enums.ResultEnum;
import com.mrjy.common.exception.InnerException;
import com.mrjy.common.util.ResultUtil;

/**
 * 全局异常处理类
 * 处理全局手动抛出的异常和未知异常并进行日志记录
 * @author Josh
 *
 */
//@ControllerAdvice
public class GlobalExceptionHandler {
	private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> handle(Exception e){
        if (e instanceof InnerException){
            return ResultUtil.error(((InnerException) e).getCode(),e.getMessage());
        }else if (e instanceof MissingServletRequestParameterException) {
        	return ResultUtil.error(ResultEnum.PARAM_ERROR);
		}else{
        	 StringWriter sw = new StringWriter();    
             PrintWriter pw = new PrintWriter(sw, true);    
             e.printStackTrace(pw);    
             pw.flush();     
             sw.flush();    
            logger.error("【系统错误】{}",sw.toString());
           return ResultUtil.error(ResultEnum.ERROR);
        }
    }
}
